# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: net_ssl_2_socket_server.py 
@time: 2019/7/17 上午11:28
"""
'''
socket版的双向认证服务端
'''
from socket import socket, AF_INET, SOCK_STREAM
import ssl


class server_ssl:
    def build_listen(self):
        CA_FILE = "client_cert.pem"
        KEY_FILE = "server_key.pem"
        CERT_FILE = "server_cert.pem"

        context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
        context.load_verify_locations(CA_FILE)
        context.verify_mode = ssl.CERT_REQUIRED

        # 监听端口
        with socket(AF_INET, SOCK_STREAM, 0) as sock:
            # 将socket打包成SSL socket
            with context.wrap_socket(sock, server_side=True) as ssl_sock:
                ssl_sock.bind(('127.0.0.1', 5678))
                ssl_sock.listen(5)
                while True:
                    # 接收客户端连接
                    client_socket, addr = ssl_sock.accept()
                    # 接收客户端信息
                    msg = client_socket.recv(8192).decode('utf-8')
                    print(f"receive msg from client {addr}:{msg}")
                    # 向客户端发送信息
                    msg = f"yes, you have client_socketect with server.\r\n".encode('utf-8')
                    client_socket.send(msg)
                    client_socket.close()


if __name__ == '__main__':
    server = server_ssl()
    server.build_listen()